home *** CD-ROM | disk | FTP | other *** search
/ HPAVC / HPAVC CD-ROM.iso / TPTUTR~1.ZIP / PASCAL06.TXT < prev    next >
Text File  |  1996-03-21  |  16KB  |  351 lines

  1.                         Turbo Pascal for DOS Tutorial
  2.                              by Glenn Grotzinger
  3.                       Part 6 -- Arrays and Their Usage.
  4.              All parts copyright 1995-96 (c) by Glenn Grotzinger
  5.  
  6.         Hello again...Let's get started...An example of the solution of
  7. the program presented in part 5 is below.
  8.  
  9. program part5;
  10.   const
  11.     income_tax = 0.15;    { set our 15% tax rate }
  12.   type
  13.     string20 = string[20];  { not needed, but good to demonstrate }
  14.   var
  15.     employee: string20;
  16.     hours, rate: real;
  17.     infile, outfile: text;
  18.     grosspay, overtimepay, intax, netpay: real;
  19.  
  20.   procedure writeheaders;   { writes the headers on our report }
  21.     begin
  22.       writeln(outfile, 'The International Widget, Inc.':51);
  23.       writeln(outfile, 'PayOut And Deductions Sheet':49);
  24.       writeln(outfile);
  25.       writeln(outfile, 'Employee', 'Hours':17, 'Rate':7, 'GrossPay':10,
  26.                        'Overtime':10, 'IncomeTax':11, 'NetPay':9);
  27.     end;
  28.  
  29.   function writeline(fillchar: char; strlength: integer):string;
  30.   { handy function that fills a certain length of a string with a fixed
  31.     character }
  32.     var                    
  33.       i: integer;
  34.       str: string;
  35.     begin
  36.       str := '';
  37.       for i := 1 to strlength do
  38.         str := str + fillchar;
  39.       writeline := str;
  40.     end;
  41.  
  42.   procedure processrecord(hrs, rate: real;var gpay, opay, itax, npay: real);
  43.     { does all of our required calculations for us }
  44.      var
  45.        rpay: real;
  46.      begin
  47.        if hrs > 40 then  { if overtime then }
  48.          begin
  49.            rpay := rate * 40;                { regular pay up to 40   }
  50.            opay := (hrs - 40) * rate * 1.5;  { overtime rate after 40 }
  51.          end
  52.        else
  53.          begin
  54.            rpay := hrs * rate; { figure as normal }
  55.            opay := 0;          { set overtime pay to 0, no overtime hours }
  56.          end;
  57.        gpay := opay + rpay;        { get our gross pay }
  58.        itax := gpay * income_tax;  { get our deduction }
  59.        npay := gpay - itax;        { actual pay to worker }
  60.      end;
  61.  
  62.   begin
  63.     assign(infile, 'WORKER.TXT');     { prepare input file  }
  64.     reset(infile);
  65.     assign(outfile, 'PAYOUT.TXT');    { prepare output file }
  66.     rewrite(outfile);
  67.     writeheaders;                         { write headers of report }
  68.     writeln(outfile, writeline('=', 72));
  69.     readln(infile, employee, hours, rate);
  70.     while not eof(infile) do { while not end of file, read,process&write }
  71.       begin
  72.         writeln('Processing ', employee);
  73.         processrecord(hours, rate, grosspay, overtimepay, intax, netpay);
  74.         writeln(outfile, employee, hours:5:2, rate:7:2, grosspay:9:2,
  75.                          overtimepay:10:2, intax:10:2, netpay:11:2);
  76.         readln(infile, employee, hours, rate);
  77.       end;
  78.     writeln('Processing ', employee);
  79.     processrecord(hours, rate, grosspay, overtimepay, intax, netpay);
  80.     writeln(outfile, employee, hours:5:2, rate:7:2, grosspay:9:2,
  81.                      overtimepay:10:2, intax:10:2, netpay:11:2);
  82.  
  83.     close(infile);
  84.     close(outfile);    { close files }
  85.   end.
  86.  
  87. The Structure of an Array
  88. =========================
  89.         For a lot of things, it is very useful to know exactly how things
  90. are done by the computer in programming.  The array is one of them.  An
  91. array is simply a group, or set of groups of like defined items.  An example
  92. of such a thing is:
  93.  
  94. firstarray: array[1..3] of integer;
  95.  
  96. What we are doing is defining three integers that we want to indicate by
  97. numbers as 1(1st), 2(2nd), and 3(3rd) in the set of integers.  Arrays are
  98. often used to correlate like items in a program to make them easier to
  99. process.  Often it is with such data as this:  Say we want to work with
  100. the high temperatures for each day of one month.  It is correlated info,
  101. so it is a very good candidate for an array.  The numbers between the []
  102. are minimum..maximum index values for the array (to keep track of which
  103. part of the array we want).  There are 31 days in a month(maximum), so we
  104. would store them as something like this:
  105.  
  106. temperatures: array[1..31] of integer;
  107.  
  108. We are defining the total number of integer units we want in the array.
  109. Which brings up the question: How is this stored in memory?
  110.  
  111. RULE: ALL MEMORY STORAGE BY COMPUTER OF ANY ITEM IS LINEAR!!!!
  112.  
  113. This rule is always helpful to remember when we work with arrays.  It
  114. does point out logic rather readily of handling arrays.  Now I will
  115. illustrate how to access items of the array.  Keep in mind that array
  116. items can be read from the keyboard or text file, and written just like
  117. variables we have worked with before.
  118.  
  119. To read the 5th temperature in the array from the keyboard, we would use
  120. something like this: readln(temperatures[5]);
  121.  
  122. Note: in addressing an array, we can even use mathematical expressions...
  123.  
  124. Usage of Arrays
  125. ===============
  126. If we wished to write out (one per line) to the screen, all the contents
  127. in the array, we would do something like this...keep in mind that array
  128. variables work exactly the same way as the variables have that we have
  129. been working with so far:
  130.  
  131. for i := 1 to 31 do
  132.   writeln(i, temperatures[i]);
  133.  
  134. Note: often for/while/repeat loops are used to work with arrays to process
  135. the whole array using an index variable in the counter.  Keep this in mind
  136. for your programming.
  137.  
  138. The indexes can be defined to be anything that was valid for use in the for
  139. loop, such as:
  140.      array1: array[1..10] of integer;
  141.      array2: array[-15..0] of real;
  142.      array3: array['a'..'z'] of char;
  143.  
  144. This naturally has limits, which you will find if you cross them (compiler
  145. warning).  What the array is of can be any valid data type.  Can we define
  146. an array of an array?  Yes.
  147.  
  148. Double Level Tables and Above
  149. =============================
  150.         We can define infinitely, as our memory allows, the number of arrays
  151. of arrays we want to define.  Say, for our temperature example, we wanted
  152. to define the limits of an array for the whole year.  We know there are
  153. 12 months in the year, so we would need 12 occurences of the array we
  154. defined previously for the high temperatures for each day:  A definition
  155. of this array would be:
  156.  
  157. temperatures: array[1..12] of array[1..31] of integer;
  158.  
  159. This is a very definable array that we could use to store all of our high
  160. temperatures for each day of the year.
  161.  
  162. Is there a shortcut, though?  Yes, there is.  You can use a comma in the
  163. first set of [] to define the limits of the 2nd array.  Why?  We see in
  164. the next paragraph.  An example of a better definition of this array is:
  165.  
  166. temperatures: array[1..12, 1..31] of integer;
  167.  
  168. We see the parts of each array in the first one there...Remember above
  169. that I said computers store things linearly.  It helps us when we know
  170. this in processing such a thing above.  Actually, for double
  171. level, triple level, etc, tables, the 2nd array, 3rd array, etc is seen as
  172. minor units within the previous defined array.  Say, we had this array:
  173.  
  174. array1: array[1..2, 1..2, 1..2] of char;
  175.  
  176. It would be set up in linear memory like this:
  177.  
  178. array1    char   char    char  char        char   char  char   char
  179.         [1,1,1] [1,1,2] [1,2,1] [1,2,2] [2,1,1] [2,1,2] [2,2,1] [2,2,2]
  180.            array1[1,1]  array[1,2]        array1[2,1]  array1[2,2]
  181.                   array1[1]                       array1[2]
  182.  
  183. I placed labels on there so we could see the layout.  It would continue
  184. ad infinitum for a 3rd level or a 4th level on anything.  So, as an
  185. example of how we can address the array of temperatures above, and work
  186. with one, here is a little code that writes 'em all to the screen, 12
  187. columns of integers (one for each month), 31 lines(one for each day
  188. in the month):
  189.  
  190. for i := 1 to 12 do
  191.   begin
  192.     for j := 1 to 31 do
  193.       write(temperatures[i, j], ' ');
  194.     writeln;
  195.   end;
  196.  
  197. Defining Constant Arrays
  198. ========================
  199. It can be done.  It's done like this:
  200.  
  201. const
  202.   months: array[1..12] of string[3] = ('Jan', 'Feb', 'Mar', 'Apr', 'May',
  203.           'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
  204.  
  205. Ord And Chr
  206. ===========
  207. These are two functions we can use to work with the ASCII table.  They
  208. are system functions.
  209.  
  210. Ord(char) gives us an integer that represents the character we put in
  211. the ()'s.  Chr(integer) gives us a character which corresponds to the
  212. ASCII code number that is given in integer.
  213.  
  214. Boolean type
  215. ============
  216. A type called boolean exists.  It can either be set to true or false.
  217.  
  218. Final Notes
  219. ===========
  220. As a final note, defining arrays, if you play around with doing that and
  221. using them (I hope you do..:>), you may get an error from the compiler
  222. that your data structure as defined is too large.  The reason is that
  223. Pascal defaults to operating and compiling your programs like they were
  224. going to work on an 8088 class machine.  The maximum addressable memory
  225. there is 64KB.  If that happens, it means you have too many variables
  226. defined.  There is a way to get around this, which will be covered in
  227. a future part of this tutorial.  Don't give up on this, and remember:
  228. Experimentation is the best tool for learning how this stuff works...
  229.  
  230. Practice Programming Problem #6
  231. ===============================
  232.         Once upon a time, a friend of yours did you a really big favor.
  233. Now they want you to repay that favor.  They are in college and doing
  234. a statistical study on the average number of times that each letter of
  235. the alphabet is used.  To accomplish that, to your unfortunate ears,
  236. your friend wants you to sit down with a sheet of paper and a book
  237. and start tallying letters on a table that's written on that sheet of
  238. paper.  You know this is very time consuming and there is probably a
  239. better way.  You realize that with your programming knowledge that you
  240. have and several text files that you have on your hard drive that you
  241. can make a program that will accomplish the task much faster.  They
  242. asked you to count through a 200 page book originally, so you decide
  243. that documentation of some shareware (5 text files) that you have are
  244. counted and summarized will do sufficiently for what your friend intends.
  245.  
  246. Write a program in Pascal and entirely Pascal that will read no more
  247. than 10 text file names from a file named FILES.TXT (you can create it,
  248. one filename (full path) per line, be sure you can find them on your
  249. drive (I recommend to get them as a whole to be no less than 200KB in
  250. size (all files combined), and as large as you want them to be as a
  251. whole -- I am only stating a good set of minimums -- the no more than 10
  252. part is a good required part of the program to do.).  For each and every
  253. file in this list, count the number of times each letter is used (whether
  254. the letter is uppercased or lowercased is irrelevant <do not differentiate,
  255. say, between A and a), do not count different cases based on that.)
  256. Then output to FRNDDATA.TXT a listing of the total numbers of each letter
  257. encountered.  Also, output other statistical data such as total number of
  258. letters encountered (better define this one as a longint or real) and
  259. total number of files used.
  260.  
  261. Notes and Hints:
  262. 1) We want counts for EACH file with EACH letter to be printed out.
  263. 2) Hint: Use an array to store the data for your numbers counted.
  264. 3) Total number of letters encountered DO NOT include numbers, wierd
  265. characters, etc, etc.  If you are foreign to the U.S. and have other
  266. characters in your alphabet than A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,
  267. R,S,T,U,V,W,X,Y, and Z and their lowercased cousins, program this
  268. utility using your alphabet.
  269. 4) Hint: Remember to take totals, we need data from ALL of our
  270. samples to be used.
  271. 5) Hint: We don't need 52 IF statements or a large case statement.
  272. Look at the ASCII table and see why I say this.
  273. 6) The program specifications say that FILES.TXT should not have more
  274. than 10 files.  If it does, just design your program to stop at file
  275. #10 and write an error message at the end of the output.
  276. 7) As with the last program, we need to write action indications to the
  277. screen so we know the program is running and has not crashed.
  278. 8) If you see negative numbers for sums, or screwy numbers, remember
  279. to initialize any arrays you may be adding things to.  Also, if you
  280. see the negative numbers, integer type overflowed (Integer max: 32000).
  281. If this happens, define all integers associated with that area to
  282. longint (Integer max: 2 billion).
  283.  
  284. Sample of FILES.TXT (It should look like this, just be sure the files
  285. you list are on your drive and are TEXT files, and not word processor
  286. files)
  287. ---------------------------------------------------------------------
  288. c:\mouse\readme.txt
  289. c:\4dos\4dos.doc
  290. d:\pastutr\pascal1.txt
  291. c:\config.sys
  292. d:\ezycom\ezy1.prn
  293.  
  294. Sample of FRNDDATA.TXT
  295. ---------------------------------------------------------------------
  296.                         Alphabetical Count Data
  297.                         for c:\mouse\readme.txt
  298.  
  299. Letter             Count                    Letter              Count
  300.   A                 12                        N                   6
  301.   B                 10                        O                   7
  302.   C                  4                        P                   2
  303.   D                 92                        Q                   2
  304.   E                 20                        R                   4
  305.   F                 32                        S                   2
  306.   G                 23                        T                   3
  307.   H                  2                        U                   4
  308.   I                  2                        V                   2
  309.   J                 34                        W                   2
  310.   K                 21                        X                   4
  311.   L                123                        Y                   5
  312.   M              12341                        Z                   2
  313.  
  314. (repeat above for rest of files in FILES.TXT)
  315.  
  316. At end:
  317. -------------------------------------------------------------------------
  318. 5 files processed.
  319. 15232 letters encountered.
  320.  
  321.                         Alphabetic Count Data
  322.                            for all files
  323.  
  324. (repeat a letter count system like we did for each file we did)
  325.  
  326.  
  327.  
  328. Next time
  329. =========
  330. We will cover the use of records, and a few other nice commands, plus a
  331. little mathematics.  Inevitably, in the sciences, math is used somewhere.
  332. We're getting to the point of needing that.  I've tried to show partial
  333. code to do things now that we're getting farther.  If people are having
  334. problems integrating the code into a program to see how it works (if you
  335. do, maybe you should work on the previous parts?), tell me and I'll go
  336. back to posting complete programs.  With reference to mathematics, if
  337. you do not know how to convert number bases, ask a parent or your favorite
  338. mathematics professor. :>
  339.  
  340. After that, we will have most of the basics covered.  That does not mean I
  341. will quit.  This is, my guess, about 2 parts away from the halfway point
  342. (don't quote me on that:>).  Anyway, there's lots more to cover, and a few
  343. special topics coming up.  To illustrate, the tutorial after the records
  344. tutorial will involve the use of DOS compatible commands, in other words
  345. those things you do in DOS (the first special topic) -- we're gonna go
  346. over how to do those things in Pascal.
  347.  
  348. Please send any comments, questions, requests for help with the sample
  349. programs (you SHOULD be doing them as you get each of these parts) to
  350. ggrotz@2sprint.net.
  351.